package com.sisyphus.spinach.ui.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;

public class StateLayout extends FrameLayout {

    public interface OnAnewRequestListener {

        void onAnewRequest();
    }


    public interface IState {

        Integer getStateCode();

        View getStateView();

        void bindParentView(StateLayout parentView);

        void display(CharSequence message, boolean visibility);

        void setOnAnewRequestListener(OnAnewRequestListener onAnewRequestListener);
    }


    public static final Integer
            FAILURE_STATE = 1, // 失败
            OFFLINE_STATE = 2, // 无网络
            LOADING_STATE = 3, // 加载
            EMPTY_STATE   = 4; // 空内容

    private int mDisplayStateLayoutCount; // 显示的状态布局数量

    private final SparseArray<IState> mStateArray = new SparseArray<>();


    public StateLayout(Context context) {
        this(context, null);
    }

    public StateLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public StateLayout addStateView(IState stateView) {
        mStateArray.put(stateView.getStateCode(), stateView);
        return this;
    }

    public void showContentView() {
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            getChildAt(i).setVisibility(i < childCount - mDisplayStateLayoutCount ? View.VISIBLE : View.GONE);
        }
    }

    public void showStateView(int stateCode) {
        this.showStateView(stateCode, null);
    }

    public void showStateView(int stateCode, CharSequence charSequence) {
        IState stateView = mStateArray.get(stateCode);

        if (stateView == null) {
            throw new IllegalStateException("没有这个状态布局，code:" + stateCode);
        }

        // 判断是否初始化，首次则初始化
        if (stateView.getStateView() == null) {
            ++mDisplayStateLayoutCount;
            stateView.bindParentView(this);
        }

        for (int i = 0; i < mStateArray.size(); i++) {
            IState view = mStateArray.get(mStateArray.keyAt(i));
            if (view.getStateView() != null) {
                view.display(charSequence, view == stateView);
                view.getStateView().setVisibility(view == stateView ? VISIBLE : GONE);
            }
        }
    }


    /**
     * 重新请求网络
     */
    public void setOnAnewRequestListener(OnAnewRequestListener onAnewRequestListener) {
        for (int i = 0; i < mStateArray.size(); i++) {
            IState stateView = mStateArray.get(mStateArray.keyAt(i));
            stateView.setOnAnewRequestListener(onAnewRequestListener);
        }
    }

}
